package sparkStream

import org.apache.kafka.clients.producer.{KafkaProducer, ProducerConfig, ProducerRecord}
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.SparkConf
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe
import org.apache.spark.streaming.kafka010.KafkaUtils
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent

import scala.collection.convert.ImplicitConversions.`map AsJavaMap`
import scala.collection.immutable.HashMap

object DstreamDemo {
  def main(args: Array[String]): Unit = {

    // Spark conf
    val conf = new SparkConf().setMaster("local[*]").setAppName("Spark Kafka Consumer")//local[*]表示本地有多少资源用多少资源
    //进行流式处理，微批次处理，间隔时间2秒
    val ssc = new StreamingContext(conf,Seconds(2)) //要到依赖
    ssc.sparkContext.setLogLevel("error")
    //配置broker,key,value,groupid,
    val kakaParams = Map[String, Object](
      "bootstrap.servers" -> "123.56.187.176:9092",//123.56.187.176
      "key.deserializer" -> classOf[StringDeserializer],
      "value.deserializer" -> classOf[StringDeserializer],
      "group.id" -> "niit",
      "enable.auto.commit" -> (false:java.lang.Boolean),
    )

    val topicName = Array("stuInfo")
    val streamRdd = KafkaUtils.createDirectStream[String,String](
      ssc,PreferConsistent,
      Subscribe[String,String](topicName,kakaParams)
    )

    //时间窗口
    val res = streamRdd.map(_.value())
    val result = res.flatMap(_.split(" ")).map((_,1)).reduceByKeyAndWindow(_+_,Seconds(4),Seconds(4))

    result.foreachRDD(
      x=>{
        println("--------------数据是--------------")
        x.foreach(println)

      }
    )

    //producer配置项
    //开始scc
    ssc.start()
    ssc.awaitTermination()//监控
  }


}
